const db = require('../utils/db');

const Todo = {
  findAllByUserId(user_id) {
    return new Promise((resolve, reject) => {
      db.all('SELECT * FROM todos WHERE user_id = ?', [user_id], (err, rows) => {
        if (err) reject(err);
        resolve(rows);
      });
    });
  },
  create(user_id, title) {
    return new Promise((resolve, reject) => {
      db.run('INSERT INTO todos (user_id, title) VALUES (?, ?)', [user_id, title], function(err) {
        if (err) reject(err);
        resolve(this.lastID);
      });
    });
  },
  update(id, title, completed) {
    return new Promise((resolve, reject) => {
      db.run('UPDATE todos SET title = ?, completed = ? WHERE id = ?', [title, completed, id], function(err) {
        if (err) reject(err);
        resolve(this.changes > 0);
      });
    });
  },
  delete(id) {
    return new Promise((resolve, reject) => {
      db.run('DELETE FROM todos WHERE id = ?', [id], function(err) {
        if (err) reject(err);
        resolve(this.changes > 0);
      });
    });
  }
};

module.exports = Todo;
